//
//  FLLShopViewController.m
//  FLLGodOfCookery
//
//  Created by LL.F on 16/8/27.
//  Copyright © 2016年 LL.F. All rights reserved.
//

#import "FLLShopViewController.h"
#import "Masonry.h"
#import "UILabel+FLLSetPropety.h"
#import "ZWYNetTool.h"
#import "FLLShopModel.h"
#import "ShopData.h"
#import "ShopScrollbanner.h"
#import "ShopCommoditytype.h"
#import "ShopImagelist.h"
#import "ShopListcommodity.h"
#import "ShopTopbanner.h"
#import "ShopVisualcodelist.h"
#import "FLLMacro.h"
#import "FLLShopTableViewCell.h"
#import "FLLMoreTableViewCell.h"
#import "FLLShopCollectionModel.h"
#import "ShopCollectionSecData.h"
#import "ShopCollectionData.h"
#import "FLLHeaderCollectionViewCell.h"
#import "UIImageView+WebCache.h"

@interface FLLShopViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
/* 假界面 */
@property (nonatomic, strong) UIView *noFoundView;
@property (nonatomic, strong) UIImageView *noFoundImage;
@property (nonatomic, strong) UILabel *noFoundLabel;

@property (nonatomic, strong) FLLShopCollectionModel *fllShopCollectionModel;
@property (nonatomic, strong) NSMutableArray<ShopCollectionSecData *> *collectionArray;
@property (nonatomic, strong) FLLShopModel *fllShopModel;
@property (nonatomic, strong) UITableView *shopTableView;
@property (nonatomic, assign) NSInteger itemCount;
@property (nonatomic, assign) NSInteger pageCount;
@property (nonatomic, assign) BOOL isSelected;
@property (nonatomic, strong) NSString *totalCount;
@property (nonatomic, strong) NSString *currentCount;
/* 头视图 */
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UICollectionView *topCollectionView;
@property (nonatomic, strong) NSArray<ShopTopbanner *> *topArray;
@property (nonatomic, strong) UICollectionView *scrollCollectionView;
@property (nonatomic, strong) NSArray<ShopScrollbanner *> *scrollArray;
@end

@implementation FLLShopViewController
- (void)viewDidLoad {
    [super viewDidLoad];
  
    // 创建加载失败View
//    [self createNoFoundView];
    
    [self createPOSTRequest];
    [self createShopTabelView];
    [self createHeaderView];
    
}
- (void)createPOSTRequest
{
    
    // 上面headerView
    [ZWYNetTool POST:@"http://api.izhangchu.com/ HTTP/1.1" andBody:@"methodName=MallHomepage&version=4.3&user_id=0&_time=&_signature=" andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type":@"application/x-www-form-urlencoded; charset=utf-8"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
        
        self.fllShopModel = [FLLShopModel modelWithDic:result];
        self.topArray = self.fllShopModel.data.topBanner;
        self.scrollArray = self.fllShopModel.data.scrollBanner;
        
        [self.topCollectionView reloadData];
        [self.scrollCollectionView reloadData];
        [self.shopTableView reloadData];
        
        } andFailureBlock:^(NSError *error) {
        
    }];
    
    // 下面collectionView
    if (_isSelected == NO) {
        _pageCount = 1;
    } else {
    
        _pageCount++;
    }
    
    NSString *bodyString = [NSString stringWithFormat:@"methodName=MallHomepageList&version=4.3&page=%ld&size=10&user_id=0&_time=&_signature=", _pageCount];
    [ZWYNetTool POST:@"http://api.izhangchu.com/ HTTP/1.1" andBody:bodyString andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type":@"application/x-www-form-urlencoded; charset=utf-8"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
        
       
        self.fllShopCollectionModel = [FLLShopCollectionModel modelWithDic:result];
        self.totalCount = [NSString stringWithFormat:@"%ld", self.fllShopCollectionModel.data.total];
        self.currentCount = [NSString stringWithFormat:@"%ld", self.fllShopCollectionModel.data.total - _pageCount * 10];
        
         if (_isSelected == NO) {
            self.collectionArray = (NSMutableArray *)self.fllShopCollectionModel.data.data;
         } else {
         
             [self.collectionArray addObjectsFromArray:(NSMutableArray *)self.fllShopCollectionModel.data.data];
             
         }
         _itemCount = _collectionArray.count;
        [self.shopTableView reloadData];
        
    } andFailureBlock:^(NSError *error) {
        
    }];
    
}
- (void)createShopTabelView
{

    self.shopTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) style:UITableViewStylePlain];
    [self.view addSubview:_shopTableView];
    self.shopTableView.delegate = self;
    self.shopTableView.dataSource  = self;
    self.shopTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.shopTableView registerNib:[UINib nibWithNibName:@"FLLShopTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"shopTableCell"];
    [self.shopTableView registerNib:[UINib nibWithNibName:@"FLLMoreTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"moreTableCell"];
    
}
- (void)createHeaderView
{

    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH , _shopTableView.bounds.size.height / 2.0)];
    [self createTopCollectionView];
    [self createScrollCollrctionView];
    


    self.shopTableView.tableHeaderView = _headerView;
}
- (void)createTopCollectionView
{

    UICollectionViewFlowLayout *topLayout = [[UICollectionViewFlowLayout alloc] init];
    topLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    topLayout.minimumInteritemSpacing = 0;
    topLayout.minimumLineSpacing = 0;
    topLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);

   
    self.topCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH , _headerView.bounds.size.height / 2.0) collectionViewLayout:topLayout];
    self.topCollectionView.delegate = self;
    self.topCollectionView.dataSource = self;
    // 怎么设置有横向滚动效果?????????
    self.topCollectionView.contentSize = CGSizeMake(10000, 0);
    self.topCollectionView.backgroundColor = [UIColor whiteColor];
    [_headerView addSubview:_topCollectionView];
    [self.topCollectionView registerNib:[UINib nibWithNibName:@"FLLHeaderCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"headerCollectionCell"];
    
    
}
- (void)createScrollCollrctionView
{

    UICollectionViewFlowLayout *scrollLayout = [[UICollectionViewFlowLayout alloc] init];
    scrollLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    scrollLayout.minimumInteritemSpacing = CellMargin;
    scrollLayout.minimumLineSpacing = CellMargin;
    scrollLayout.sectionInset = UIEdgeInsetsMake(CellMargin, CellMargin, CellMargin, CellMargin);
    
    
    self.scrollCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, _headerView.bounds.size.height / 2.0, SCREEN_WIDTH , _headerView.bounds.size.height / 2.0) collectionViewLayout:scrollLayout];
    self.scrollCollectionView.delegate = self;
    self.scrollCollectionView.dataSource = self;
    self.scrollCollectionView.showsHorizontalScrollIndicator = NO;
    self.scrollCollectionView.backgroundColor = [UIColor whiteColor];
    [_headerView addSubview:_scrollCollectionView];
    [self.scrollCollectionView registerNib:[UINib nibWithNibName:@"FLLHeaderCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"headerCollectionCell"];
    
}
- (void)createNoFoundView
{
    self.noFoundView = [[UIView alloc] init];
    [self.view addSubview:_noFoundView];
    [_noFoundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(0);
    }];
    self.noFoundImage = [[UIImageView alloc] init];
    _noFoundImage.image = [UIImage imageNamed:@"noFound"];
    [_noFoundView addSubview:_noFoundImage];
    [_noFoundImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(177 / 2.0);
        make.width.mas_equalTo(117 / 2.0);
        make.centerX.mas_equalTo(0);
        make.centerY.mas_equalTo(self.view.mas_centerY).multipliedBy(0.8);
    }];
    self.noFoundLabel = [[UILabel alloc] init];
    _noFoundLabel.text = @"网络不给力, 请检查网络, 点击屏幕重试!";
    _noFoundLabel.numberOfLines = 0;
    [_noFoundView addSubview:_noFoundLabel];
    [_noFoundLabel setPropetyWithTextColor:[UIColor blackColor] Alignment:1 textFont:[UIFont systemFontOfSize:17]];
    [_noFoundLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0).multipliedBy(1.1);
        make.centerX.mas_equalTo(0);
        make.width.mas_equalTo(200);
    }];
    

}

#pragma mark -- TableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    
    return 2;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.row == 0) {
        FLLShopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"shopTableCell"];
    cell.collectionArray = (NSMutableArray *)_collectionArray;
    return cell;
    }
    FLLMoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"moreTableCell"];
    cell.grayLabel.text = [NSString stringWithFormat:@"还有%@个热卖商品", _currentCount];
    cell.grayLabel.font = [UIFont systemFontOfSize:16 * kWidthScale];
    cell.grayLabel.backgroundColor = [UIColor colorWithRed:0.87 green:0.87 blue:0.87 alpha:1.00];
    cell.contentView.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    return cell;
    
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{

    return @"热门商品";
}
// 取消分区头悬浮效果
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = 60 * kHeightScale;
    if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0) {
        scrollView.contentInset = UIEdgeInsetsMake(- scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(- sectionHeaderHeight, 0, 0, 0);
    }
}
// cell 高度自适应
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.row == 0) {
        if (_itemCount % 2 == 0) {
            return (_itemCount / 2 * (SCREEN_WIDTH - CellMargin) / 2.0 * 1.5 + (_itemCount / 2 + 1) * CellMargin) ;
        }
        return ((_itemCount / 2 + 1 ) * (SCREEN_WIDTH - CellMargin) / 2.0 * 1.5 + (_itemCount / 2 + 1) * CellMargin) ;
    } else {
        
        if (_currentCount <= 0) {
            return 0;
        }
        return 60 * kHeightScale;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 60 * kHeightScale;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.row == 1) {
        _isSelected = YES;
        [self createPOSTRequest];
        
    }
}
#pragma mark -- CollectionView DataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    if (collectionView == _topCollectionView) {
        return 1;
    }
    return _scrollArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    if (collectionView == _topCollectionView) {
        FLLHeaderCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"headerCollectionCell" forIndexPath:indexPath];
    [cell.mainImageView sd_setImageWithURL:[NSURL URLWithString:_topArray[indexPath.row].bannerPicture] placeholderImage:[UIImage new] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
    }];
    
    return cell;
    } else {
        
       FLLHeaderCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"headerCollectionCell" forIndexPath:indexPath];
        [cell.mainImageView sd_setImageWithURL:[NSURL URLWithString:_scrollArray[indexPath.row].bannerPicture] placeholderImage:[UIImage new] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
        }];
        
        return cell;
        
    }
    
    
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{

    if (collectionView == _topCollectionView) {
        return CGSizeMake(_topCollectionView.bounds.size.width, _topCollectionView.bounds.size.height);
    }
    return CGSizeMake((_scrollCollectionView.bounds.size.width - 3 * CellMargin) / 2.0, _scrollCollectionView.bounds.size.height - 2 * CellMargin);
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
